<?php

namespace App\Console\Commands;

use App\Models\Base\ServerList;
use App\Models\Base\StatEverdayPlayer;
use App\Service\PlayerService;
use Illuminate\Support\Facades\Log;

class FetchEverydayPlayer extends CommandBase
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'fetch:everyday';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '统计每天登陆玩家数量';

    /**
     * Create a new command instance.
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        //获取所有游戏数据库配置
        $list = ServerList::all()->pluck('server_id');
        if (!$list) {
            return false;
        }
        foreach ($list as $server_id) {
            //设置数据库配置
            setDB($server_id);
            $num = PlayerService::getTodayPlayerNum($this->yesterdayTimestamp, $this->todayTimestamp)->count();
            //写入统计表
            $this->save($server_id, $num);
        }
    }

    /**
     * [save 写入本地统计表].
     *
     * @Author   王文凡
     * @DateTime 2018-04-21
     *
     * @version  1.0
     *
     * @param [type] $server_id [description]
     * @param [type] $num       [description]
     *
     * @return [type] [description]
     */
    protected function save($server_id, $num)
    {
        $model = new StatEverdayPlayer();
        $model->server_id = $server_id;
        $model->number = $num;
        $model->day = $this->yesterday;
        if ($model->save()) {
            echo 'success';
            Log::info('统计当前玩家数量成功', ['server_id' => $server_id, 'num' => $num]);
        } else {
            Log::error('统计当前玩家数量失败', ['server_id' => $server_id, 'num' => $num]);
            echo 'error';
        }
        $model = null;
    }
}
